package com.zahb.qadx.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.appcompat.widget.ListPopupWindow;
import androidx.collection.SparseArrayCompat;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseDelegateMultiAdapter;
import com.chad.library.adapter.base.delegate.BaseMultiTypeDelegate;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.google.gson.Gson;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.zahb.qadx.R;
import com.zahb.qadx.base.BaseActivityV2;
import com.zahb.qadx.databinding.ActivityCurriculumListBinding;
import com.zahb.qadx.model.Category;
import com.zahb.qadx.model.CommonData;
import com.zahb.qadx.model.Curriculum;
import com.zahb.qadx.net.RetrofitService;
import com.zahb.qadx.skeleton.RecyclerViewSkeletonScreen;
import com.zahb.qadx.skeleton.Skeleton;
import com.zahb.qadx.ui.popup.PopupCurriculumCategory;
import com.zahb.qadx.ui.view.adapter.MBaseAdapter;
import com.zahb.qadx.ui.view.adapter.MViewHolder;
import com.zahb.qadx.ui.view.decoration.MColorDrawable;
import com.zahb.qadx.ui.view.decoration.MDividerItemDecoration;
import com.zahb.qadx.util.CompatHelper;
import com.zahb.qadx.util.Constant;
import com.zahb.qadx.util.DisplayUtil;
import com.zahb.qadx.util.ImageLoaderKt;
import com.zahb.qadx.util.Tips;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * 全部课程
 */
public class CurriculumListActivity extends BaseActivityV2 implements OnRefreshLoadMoreListener {

    ConstraintLayout mTitleLayout;
    AppCompatTextView mTvSort;
    AppCompatTextView mTvCategory;
    SmartRefreshLayout mRefreshLayout;
    RecyclerView mRecyclerView;

    private final String[] mSortArray = new String[]{"综合排序", "最新", "最热"};
    private ListPopupWindow mCurriculumSortPopup;

    private PopupCurriculumCategory mPopupCurriculumCategory;
    private List<Category> mCategoryList;

    private int mCurrentPage = 1;
    private static final int PAGE_SIZE = 10;
    private Category mSelectedCategory;
    private int mSourceId;
    private BaseDelegateMultiAdapter<Curriculum, BaseViewHolder> mCurriculumAdapter;

    private RecyclerViewSkeletonScreen mSkeletonScreen;
    private long mSkeletonShowTime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mSourceId = getIntent().getIntExtra("sourceId", -1);
        if (mSourceId != -1) {
            mSelectedCategory = new Category();
            mSelectedCategory.setId(mSourceId);
        }
        getCategoryData();
        //mRefreshLayout.autoRefresh();
        onRefresh(mRefreshLayout);
        showSkeleton();
        tryToSwitch();
    }

    private void tryToSwitch() {
        SharedPreferences settings = getActivity().getSharedPreferences("tryToSwitch", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = settings.edit();
        editor.putInt("tryToSwitch", 1);//默认1
        editor.apply();
        addDisposable(RetrofitService.getNetService()
                .getTryToSwitch(2)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    if (response.getStatusCode() == Constant.CODE_SUCCESS) {
                        //Use 0 or MODE_PRIVATE for the default operation
                        editor.putInt("tryToSwitch", response.getData()); //1  H5  2 原生
                        editor.commit();
                    } else {
                        showBindToast(response.getErrorInfo());
                    }
                }, Throwable::printStackTrace));
    }

    @Override
    public void initViewBinding() {
        ActivityCurriculumListBinding binding = ActivityCurriculumListBinding
                .inflate(getLayoutInflater(), mContainer, true);
        mTitleLayout = binding.titleLayout;
        mTvSort = binding.tvSort;
        mTvSort.setOnClickListener(this);
        mTvCategory = binding.tvCategory;
        mTvCategory.setOnClickListener(this);
        mRefreshLayout = binding.refreshLayout;
        mRecyclerView = binding.recyclerView;
    }

    @Override
    protected void initViews() {
        mTopBarDivider.setVisibility(View.VISIBLE);
        mTvSort.setText(mSortArray[0]);
        mTvSort.setTag(false);
        mTvCategory.setText(getString(R.string.all_curriculum));
        mTvCategory.setTag(false);

        mRefreshLayout.setOnRefreshLoadMoreListener(this);
        mRefreshLayout.setEnableLoadMoreWhenContentNotFull(false);

        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        MDividerItemDecoration itemDecoration = new MDividerItemDecoration(getContext());
        MColorDrawable colorDrawable = new MColorDrawable(CompatHelper.getColor(R.color.gray_999999));
        colorDrawable.setIntrinsicWidth(1).setIntrinsicHeight(1);
        itemDecoration.setDrawable(colorDrawable);
        itemDecoration.setShowLast(true);
        mRecyclerView.addItemDecoration(itemDecoration);
        mCurriculumAdapter = new BaseDelegateMultiAdapter<Curriculum, BaseViewHolder>() {
            {
                setMultiTypeDelegate(new BaseMultiTypeDelegate<Curriculum>() {
                    @Override
                    public int getItemType(@NotNull List<? extends Curriculum> list, int i) {
                        if (TextUtils.equals(list.get(i).getCourseType(), "1"))
                            return 1;
                        else
                            return 0;
                    }
                });
                assert getMultiTypeDelegate() != null;
                getMultiTypeDelegate().addItemType(0, R.layout.item_list_curriculum);
                getMultiTypeDelegate().addItemType(1, R.layout.item_list_curriculum_h);
            }

            @Override
            protected void convert(@NotNull BaseViewHolder baseViewHolder, Curriculum curriculum) {
                ImageLoaderKt.loadImageSameCorners(baseViewHolder.getView(R.id.iv_icon), curriculum.getCoverImage(), 5f);
                baseViewHolder.setText(R.id.tv_name, curriculum.getName())
                        .setText(R.id.tv_desc, CompatHelper.isEmpty(curriculum.getSubName()) ? "该课程暂无副标题" : curriculum.getSubName())
                        .setText(R.id.tv_category, curriculum.getCateName());
            }
        };
        mCurriculumAdapter.setOnItemClickListener((adapter1, view, position) ->
                CurriculumDetailsActivity.actionStart(getContext(), mCurriculumAdapter.getItem(position), CurriculumDetailsActivity.TYPE_FROM_HOME));
        mRecyclerView.setAdapter(mCurriculumAdapter);
    }

    @Override
    protected int getTitleStringRes() {
        return R.string.all_curriculum;
    }

    private void showSkeleton() {
        mRefreshLayout.setEnableRefresh(false);
        mSkeletonScreen = Skeleton.bind(mRecyclerView)
                .adapter(mCurriculumAdapter)
                .shimmer(true)
                .shimmerMode(RecyclerViewSkeletonScreen.SHIMMER_MODE_ITEM_CHILD)
                .angle(15)
                .frozen(true)
                //.color(R.color.black_333333)
                .duration(1000)
                .count(10)
                .load(R.layout.item_list_curriculum_skeleton)
                .show();
        mSkeletonShowTime = System.currentTimeMillis();
    }

    private void hideSkeleton() {
        if (mSkeletonScreen != null) {
            long currentTime = System.currentTimeMillis();
            if (currentTime - mSkeletonShowTime > Constant.MIN_NETWORK_TIME) {
                mRefreshLayout.setEnableRefresh(true);
                mSkeletonScreen.hide();
                mSkeletonScreen = null;
            } else {
                addDisposable(Observable.timer(mSkeletonShowTime + Constant.MIN_NETWORK_TIME - currentTime, TimeUnit.MILLISECONDS)
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(aLong -> hideSkeleton()));
            }
        }
    }

    private void getCategoryData() {
        Map<String, Object> params = new HashMap<>();
        params.put("pageSize", -1);
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), new Gson().toJson(params));
        addDisposable(RetrofitService.getNetService()
                .getCurriculumCategoryList(body)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    if (response.getStatusCode() == 200) {
                        SparseArrayCompat<SparseArrayCompat<Category>> array = recapitalizeCategoryData(response.getData());
                        mCategoryList = new ArrayList<>();
                        SparseArrayCompat<Category> arrayLevel1 = array.get(1);
                        if (arrayLevel1 != null) {
                            for (int i = 0; i < arrayLevel1.size(); i++) {
                                Category category = arrayLevel1.valueAt(i);
                                if (mSourceId == category.getId()) {
                                    mTvCategory.setText(category.getName());
                                }
                                mCategoryList.add(category);
                            }
                        }
                    }
                }, Throwable::printStackTrace));
    }

    private SparseArrayCompat<SparseArrayCompat<Category>> recapitalizeCategoryData(CommonData<Category> dataCategory) {
        // 先按照level分组
        SparseArrayCompat<SparseArrayCompat<Category>> array = new SparseArrayCompat<>();
        for (int i = 0; i < dataCategory.getList().size(); i++) {
            Category category = dataCategory.getList().get(i);
            int level = category.getLevel();
            SparseArrayCompat<Category> categoryList = array.get(level);
            if (categoryList == null)
                categoryList = new SparseArrayCompat<>();
            categoryList.put(category.getId(), category);
            array.put(level, categoryList);
        }

        for (int i = 1; i < array.size(); i++) {
            SparseArrayCompat<Category> parentArray = array.get(i);
            SparseArrayCompat<Category> childArray = array.get(i + 1);
            if (childArray != null) {
                for (int j = 0; j < childArray.size(); j++) {
                    Category categoryChild = childArray.valueAt(j);
                    if (parentArray != null) {
                        Category categoryParent = parentArray.get(categoryChild.getParentId());
                        if (categoryParent != null) {
                            List<Category> childList = categoryParent.getChildList();
                            if (childList == null)
                                childList = new ArrayList<>();
                            childList.add(categoryChild);
                            categoryParent.setChildList(childList);
                        }
                    }
                }
            }
        }
        return array;
    }

    public static void actionStart(Context context, int sourceId) {
        Intent intent = new Intent(context, CurriculumListActivity.class);
        intent.putExtra("sourceId", sourceId);
        context.startActivity(intent);
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        if (view.getId() == R.id.tv_sort) {
            if ((boolean) mTvCategory.getTag()) {
                mPopupCurriculumCategory.dismiss();
            }

            if ((boolean) mTvSort.getTag()) {
                mCurriculumSortPopup.dismiss();
            } else {
                mCurriculumSortPopup = getCurriculumSortPopup(mTvSort, mSortArray);
                mCurriculumSortPopup.show();
                updateCurriculumSortPopupUI(mCurriculumSortPopup);
                afterShowPopup(mTvSort);
            }
        } else if (view.getId() == R.id.tv_category) {
            if ((boolean) mTvSort.getTag()) {
                mCurriculumSortPopup.dismiss();
            }

            if ((boolean) mTvCategory.getTag()) {
                mPopupCurriculumCategory.dismiss();
            } else {
                if (mCategoryList == null)
                    mCategoryList = new ArrayList<>();
                mPopupCurriculumCategory = getPopupCurriculumCategory(mTvCategory, mCategoryList, mSourceId);
                mPopupCurriculumCategory.showAsDropDown(mTitleLayout, 0, 0, Gravity.BOTTOM);
                afterShowPopup(mTvCategory);
            }
        }
    }

    // 初始化分类列表 PopupWindow
    private PopupCurriculumCategory getPopupCurriculumCategory(TextView textView, List<Category> list, int sourceId) {
        if (mPopupCurriculumCategory == null) {
            mPopupCurriculumCategory = new PopupCurriculumCategory(getContext(), R.layout.item_list_curriculum_sort, list, sourceId);
            mPopupCurriculumCategory.setOnCategorySelectedListener(category -> {
                if (mSelectedCategory == null || mSelectedCategory.getId() != category.getId()) {
                    if (category.getId() == -1)
                        textView.setText(mPopupCurriculumCategory.mDefaultStr);
                    else
                        textView.setText(category.getName());
                    mSelectedCategory = category;
                    mRefreshLayout.autoRefresh();
                }
            });
            mPopupCurriculumCategory.setOnDismissListener(() -> afterDismissPopup(textView));
        }
        return mPopupCurriculumCategory;
    }

    // 隐藏 PopupWindow 后续
    private void afterDismissPopup(TextView textView) {
        textView.setTag(false);
        textView.setTextColor(CompatHelper.getColor(R.color.black_303133));
    }

    // 显示 PopupWindow 后续
    private void afterShowPopup(TextView textView) {
        textView.setTag(true);
        textView.setTextColor(CompatHelper.getColor(R.color.red_ff4500));
    }

    // 更新排序方式 PopupWindow 的显示效果
    private void updateCurriculumSortPopupUI(ListPopupWindow popupWindow) {
        ListView listView = popupWindow.getListView();
        if (listView != null) {
            ((ViewGroup) listView.getParent()).setBackgroundColor(CompatHelper.getColor(R.color.white_ffffff));
            ((ViewGroup) listView.getParent()).setElevation(0f);
            listView.setVerticalScrollBarEnabled(false);
            listView.setDivider(ContextCompat.getDrawable(getContext(), R.drawable.default_divider));
            listView.setSelector(new ColorDrawable(CompatHelper.getColor(R.color.transparent)));
            ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) listView.getLayoutParams();
            lp.setMarginStart(DisplayUtil.dip2px(16f));
            lp.setMarginEnd(DisplayUtil.dip2px2(16f));
            listView.setLayoutParams(lp);
        }
    }

    // 初始化排序方式 PopupWindow
    private ListPopupWindow getCurriculumSortPopup(TextView textView, String[] items) {
        if (mCurriculumSortPopup == null) {
            mCurriculumSortPopup = new ListPopupWindow(getContext());
            SortAdapter adapter = new SortAdapter(getContext(), R.layout.item_list_curriculum_sort, Arrays.asList(items));
            int index = Arrays.asList(items).indexOf(textView.getText().toString().trim());
            adapter.setSelectPos(index);
            mCurriculumSortPopup.setAdapter(adapter);
            mCurriculumSortPopup.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
            mCurriculumSortPopup.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
            mCurriculumSortPopup.setAnimationStyle(R.style.PortraitPoPupWindow);
            mCurriculumSortPopup.setAnchorView(mTitleLayout);
            mCurriculumSortPopup.setModal(true);
            mCurriculumSortPopup.setBackgroundDrawable(new ColorDrawable(0x50000000));
            mCurriculumSortPopup.setOnItemClickListener((parent, view, position, id) -> {
                adapter.setSelectPos(position);
                adapter.notifyDataSetChanged();
                mCurriculumSortPopup.dismiss();
            });
            mCurriculumSortPopup.setOnDismissListener(() -> {
                textView.setText(items[adapter.getSelectPos()]);
                afterDismissPopup(textView);
            });
        }
        return mCurriculumSortPopup;
    }

    private void getCourseList(Category category) {
        Map<String, Object> params = new HashMap<>();
        params.put("startPage", mCurrentPage);
        params.put("pageSize", PAGE_SIZE);
        params.put("listType", 0);
        if (category != null && category.getId() != -1)
            params.put("cateId", category.getId());
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), new Gson().toJson(params));
        addDisposable(RetrofitService.getNetService()
                .getCurriculumList(body)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    mRefreshLayout.finishRefresh();
                    mRefreshLayout.finishLoadMore(1000);
                    if (response.getStatusCode() == 200) {
                        if (response.getData() != null) {
                            if (mCurrentPage == 1) {
                                mCurriculumAdapter.setList(response.getData().getList());
                            } else {
                                mCurriculumAdapter.addData(response.getData().getList());
                            }
                        }
                    } else {
                        showBindToast(response.getErrorInfo());
                    }
                    hideSkeleton();
                }, throwable -> {
                    throwable.printStackTrace();
                    Tips.RequestError(getActivity());
                    mRefreshLayout.finishRefresh();
                    mRefreshLayout.finishLoadMore(1000);
                    hideSkeleton();
                }));
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        int size = mCurriculumAdapter.getItemCount();
        if (size % PAGE_SIZE == 0) {
            mCurrentPage = size / PAGE_SIZE + 1;
        } else {
            mCurrentPage = size / PAGE_SIZE + 2;
        }
        getCourseList(mSelectedCategory);
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        mCurrentPage = 1;
        getCourseList(mSelectedCategory);
    }

    private static class SortAdapter extends MBaseAdapter<String> {

        private int mSelectPos = -1;

        int getSelectPos() {
            return mSelectPos;
        }

        void setSelectPos(int selectPos) {
            mSelectPos = selectPos;
        }

        SortAdapter(@NonNull Context context, int layoutId, @NonNull List<String> list) {
            super(context, layoutId, list);
        }

        @Override
        public void convert(int position, MViewHolder holder, String item) {
            TextView textView = holder.getView(R.id.text_view);
            textView.setText(item);
            if (position == mSelectPos) {
                textView.setTextColor(CompatHelper.getColor(R.color.red_ff4500));
            } else {
                textView.setTextColor(CompatHelper.getColor(R.color.black_303133));
            }
        }
    }
}
